;(function(){
	if (window.know) {
		return;
	}
	function httpGet(url, data, options = {}) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "get",
                url,
                data,
                dataType: "json",
				timeout: 1e4,
                success: (result) => {
                    if (result.code === 0) {
                        reject(result);
                    } else {
                        resolve(result);
                    }
                },
                error: (xhr) => {
                    reject(xhr);
                },
                ...options,
            });
        }).catch((err) => {
            console.warn(err);
            noty({
                text: err?.msg || err?.responseJSON?.message || '未知错误',
                type: 'error',
                layout:'topCenter',
            });
            return Promise.reject(err);
        });        
    }

    function httpPost(url, data, options = {}) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "post",
                url,
                data,
                dataType: "json",
				timeout: 1e4,
                success: (result) => {
                    if (result.code === 0) {
                        reject(result);
                    } else {
                        resolve(result);
                    }
                },
                error: (xhr) => {
                    reject(xhr);
                },
                ...options,
            });
        }).catch((err) => {
            console.warn(err);
            noty({
                text: err?.msg || err?.responseJSON?.message || '未知错误',
                type: 'error',
                layout:'topCenter',
            });
            return Promise.reject(err);
        });        
    }
	
	const http = {
		httpGet,
		httpPost
	};
	
	function formValidRules(formSelector, validSelector, success) {
        const elems = $(`${formSelector} ${validSelector}`); 
		const rules = {};
		const messages = {};
		for (const elem of elems) {
			const required = $(elem).data('rule-required');
			if (required) {
				const msg = $(elem).data('msg-required');
				const name = $(elem).attr('name');
				
				rules[name] = { required: true };
				messages[name] = { required: msg };				
			}
		}	
		console.warn('formValidRules', formSelector, validSelector, success);
        console.warn('formValidRules-elems', elems);
        console.warn('formValidRules-rules', rules);
        console.warn('formValidRules-messages', messages);

		$(formSelector).validate({
            debug: true,
            rules,
            messages,
            submitHandler: success,
			showErrors: function(errorMap, errorList) {
                console.warn("showErrors", errorMap, errorList);
				const items = $(`${formSelector} ${validSelector}`);
				for (const item of items) {
					const errItem = errorList.find((errItem) => item === errItem.element);
                    console.warn("errItem", errItem);
					if (errItem) {
                        console.warn("errItem", errItem);
						if (!errItem.element.nextElementSibling || false === $(errItem.element.nextElementSibling).hasClass("error")) {
							$(`<label for="${$(errItem.element).attr('name')}" generated="true" class="error">${errItem.message}</label>`).insertAfter(errItem.element);
						}
                        if ($(item).hasClass("error") || $(item).next()?.hasClass("error")) {
                            $(item).next().show();
                        }
						$(item).parent().parent().addClass("has-error");
					} else {
                        console.warn("item", item);
                        if ($(item).hasClass("error") || $(item).next()?.hasClass("error")) {
                            $(item).next()?.hide();
                        }
						$(item).parent().parent().removeClass("has-error");
					}
				}
			},
        });		
    }
	
	function editInit(formSelector, initSelector, item) {
		console.warn('editInit', formSelector, initSelector, item);

        const elems = $(`${formSelector} ${initSelector}`); 
		for (const elem of elems) {
			const name = $(elem).attr('name');
            console.warn(name, item[name]);
			$(elem).val(item[name]);
		}
    }
	
    function bootstrapConfig() {
        return {
            method: "get", 
            dataType: "json",
            contentType: "application/json,charset=utf-8",
            uniqueId: "id",
            height: window.frameElement.offsetHeight - 140,
            queryParamsType: "limit",  
            striped: true,
			clickToSelect: true,
			showColumns: true,
            showRefresh: true,
			pagination: true,
            sidePagination: "server",
            pageNumber: 1,
            pageSize: 10,
            pageList: [10, 25, 50, 100],
            paginationPreText: "上一页",
            paginationNextText: "下一页",
            paginationFirstText: "首页",
            paginationLastText: "未页",
            responseHandler: function ({ data = [] }) {
				return data;
            },
        };
    }

    const bootstrap = {
        config: bootstrapConfig,
    }

	const form = {
		formValidRules,
		editInit,
	};

    const util = {
        debounce: function debounce(fn, delay) {
            let timer;
            return function _debounce() {
                if (timer) clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.apply(this, arguments);
                }, delay);
            }
        },
    };

	const KNOW = { http, form, bootstrap, util };
	
	window.know = KNOW;
})();